package com.example.project.webControlleer;

import com.example.project.dao.ParkingDAO;
import com.example.project.dao.UserDAO;
import com.example.project.dao.WalletHistroyDAO;
import com.example.project.pojo.Parking;
import com.example.project.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Date;

@Controller
@RequestMapping("web")
public class WebRenewalParkingController {
    @RequestMapping("renewal")
    public String renewal(Model model, HttpServletRequest request) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        ParkingDAO parkingDAO = new ParkingDAO();
        Parking parking = parkingDAO.findParkingByID(id);
        model.addAttribute("parking", parking);
        return "/web/renewalParking";
    }

    @RequestMapping("parkingRenewal")
    public String parkingRenewal(Parking parking, int year, HttpSession session, double money) {
        ParkingDAO parkingDAO =new ParkingDAO();
     int days =   parkingDAO.FindEndTime(parking.getEndTime());
        if (days >= 0) {
            Date endTime = parking.getEndTime();
            endTime.setYear(endTime.getYear() + year);
            parking.setEndTime(endTime);
        } else {
            parking.yearTime(year);
        }
        parkingDAO.renewal(parking);
        UserDAO userDAO = new UserDAO();
        User user = (User) session.getAttribute("user");
        user.setTotalMoney(userDAO.findTotalMoneyByID(user.getId()));
        userDAO.charge(0 - money * year, user);
        session.setAttribute("user",user);
        WalletHistroyDAO walletHistroyDAO = new WalletHistroyDAO();
        walletHistroyDAO.parkingHistory(parking, user, money * year);
        return "redirect:/web/findPrivateParking";
    }
}
